package com.dylan.channel.v3;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor{

    public  void register(SocketChannel channel){
        this.execute(new Runnable() {
            @Override
            public void run() {
                register0(channel);
            }
        });
    }
    private void register0(SocketChannel channel) {
        try {
            channel.configureBlocking(false);
            channel.register(getSelect(), SelectionKey.OP_READ);
            logger.info("接受到客户端连接:"+channel.getRemoteAddress().toString());
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            buffer.put("该客户端已经连接成功".getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            channel.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract Selector getSelect();
}
